package com.gray.blog.interceptor;

import com.gray.blog.common.arg.BaseArg;
import com.gray.blog.common.enums.ErrorCodeEnum;
import com.gray.blog.common.util.JWTUtil;
import com.gray.blog.common.util.ResultUtil;
import com.gray.blog.dao.sys.SysUserDao;
import com.gray.blog.entity.sys.SysUserEntity;
import com.gray.blog.interceptor.pointcut.ControllerPointCut;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Created  By zhoux 2019/04/16
 **/
@Slf4j
@Aspect
@Order(2)
@Component
public class SysInterceptor extends ControllerPointCut {

    @Autowired
    private SysUserDao sysUserDao;

    @Around("sysControllerMethod()")
    public Object sysInterceptor(ProceedingJoinPoint joinPoint) throws Throwable{
        Object result = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            log.error("SysInterceptor.sysInterceptor token not found");
            ResultUtil.buildErrorResult(ErrorCodeEnum.TOKEN_NOT_FOUND, response);
            return null;
        }
        String userName = JWTUtil.getUsername(token);
        SysUserEntity sysUserEntity = sysUserDao.getInfoByLoginName(userName);
        if (sysUserEntity == null) {
            log.error("SysInterceptor.sysInterceptor sysUserEntity is null token:{}, userName:{}",token, userName);
            ResultUtil.buildErrorResult(ErrorCodeEnum.SYS_USER_NOT_FOUND, response);
            return null;
        }
        Object[] arguments = joinPoint.getArgs();
        if (arguments.length > 0) {
            // 初始化基础数值
            if (arguments[0] instanceof BaseArg) {
                BaseArg baseArg = (BaseArg) arguments[0];
                baseArg.setUserId(sysUserEntity.getId());
                baseArg.setUserName(sysUserEntity.getLoginName());
            }
        }
        result = joinPoint.proceed();
        return result;
    }

}
